<template lang="pug">
    div(v-show="field")
        el-upload(:action="toAction(field.action)" 
                    list-type="picture-card" 
                    :auto-upload="false" 
                    :on-preview="handlePictureCardPreview"
                    :on-remove="handleRemove"
                    accept=""
                    :multiple="true"
                    :headers="headers"
                    :disabled="field.readonly"
                    :limit="1"
                    :on-error="upload_fail"
                    :on-success="upload_success"
                    :on-change="on_change"
                    :file-list="uploadedFileList"
                    ref="uploader")
            i(slot="default" class="el-icon-plus" v-if="fileList.length === 0")
            i(slot="default" class="el-icon-minus" v-else)
        <!--缩略图预览弹窗-->
        el-dialog(:visible.sync="dialogThumbVisible")
            img(width="100%" :src="dialogThumbUrl" alt="")
</template>
<script>
import axios from "../../../plugins/axios";
import { Message } from "element-ui";
import util from "../../../libs/util";
import UtilMixin from "./util-mixin";

export default {
  name: "uploader",
  mixins: [UtilMixin],
  data() {
    return {
      dialogThumbVisible: false,
      dialogThumbUrl: null,
      fileList: [],
      upload_success_callback: null,
      uploaded: []
    };
  },
  props: {
    field: { type: Object }
  },
  
  model: { prop: "imgs", event: "update" },

  computed: {
    headers() {
		const token = this.$store.state.base.token;
      return { Authorization: "Bearer " + token };
    },
    
    uploadedFileList() {
      if (!this.field) return [];
      if (!this.field.mapVal) return [];

      const field = this.field;

      let result = [];
      const mapValType = Object.prototype.toString.call(field.mapVal);
      if (mapValType === "[object Array]") {
        field.mapVal.forEach(val => {
          const valType = Object.prototype.toString.call(val);

          switch (valType) {
            case "[object String]":
              result.push({
                url: this.toAction(val),
                name: val.split("/")[val.split("/").length - 1]
              });
              break;
            case "[object Object]":
              result.push({
                url: this.toAction(val.url || val.action),
                name: val.name || val.id
              });
              break;
          }
        });
      } else if (mapValType === "[object String]") {
        result.push({
          url: this.toAction(field.mapVal),
          name: field.mapVal.split("/")[field.mapVal.split("/").length - 1]
        });
      }

      return result;
    }
  },
  methods: {
    submit(callback) {
      if (this.fileList.length === 0) {
        if (callback) callback([]);
        return;
      }
      // 判断是不是有没上传成功的
      const index = this.fileList.findIndex(file => {
        return file.status != "success";
      });
      // 如果没有 调用方法 全部上传成功的数据不会处罚上传
      if (index == -1) {
        if (callback) callback(this.uploaded);
        return;
      }

      if (callback) this.upload_success_callback = callback;
      this.$refs.uploader.submit();
    },
    handleRemove(file, fileList) {
      const ui = file.uid;
      var index = this.uploaded.findIndex(file => {
        return file.uid == uid;
      });
      if (index !== -1) this.uploaded.splice(index, 1); // 已上传的也要删除
      this.fileList = fileList;
    },
    on_change(file, fileList) {
      this.fileList = fileList;
    },
    handlePictureCardPreview(file) {
      this.dialogThumbUrl = file.url;
      this.dialogThumbVisible = true;
    },
    upload_fail(err) {
      Message.error("图片文件上传失败，提交终止！");
      this.$emit("uplod-fail");
    },
    upload_success(res, file) {
      let data = res.result;
      data.uid = file.uid; // 识别未上传的图片
      //   const id = res.id;
      // const url = res.url;
      this.uploaded.push(data);
      if (this.upload_success_callback)
        this.upload_success_callback(this.uploaded);
    },
    clear() {
      this.$refs.uploader.clearFiles();
      this.fileList = [];
    }
  }
};
</script>
